package com.ywgt.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;

public class ReadWriteLockTest {
    public static void main(String[] args) {
        MyCache cache=new MyCache();
        for (int i = 0; i < 10; i++) {
            final int temp=i;
            new Thread(()->{
                cache.put(temp+"",temp);
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            final int temp=i;
            new Thread(()->{
                cache.get(temp+"");
            }).start();
        }

    }
}
class MyCache{
    private Map<String, Object> cache=new HashMap<>();
    //读写锁 写入时保证只有一个线程操作
    ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    public void put(String key,Object value){
            readWriteLock.writeLock().lock();
        try {
            System.out.println(key+"存");
            cache.put(key,value);
            System.out.println(key+"存ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public Object get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(key+"取");
            return cache.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return null;
    }
}